<template>
	<view class="add-house-info">
		<view class="house-title">
			<view class="title">
				房屋信息
			</view>
			<view class="content">
				{{title}}
			</view>
		</view>
		<view class="houseOwner-info">
			<view class="title">
				业主信息
			</view>
			
			<u--form 
			  labelPosition="left"
			  :model="houseOwnerInfo"
			  :rules="rules"
			  ref="form1"
			  labelWidth="208rpx"
			  :labelStyle="{
				  backgroundColor: '#fff',
				  padding:'30rpx'
			  }">
				<u-form-item
					label="姓名"
					prop="name"
					borderBottom
				>
					<u--input
						v-model="houseOwnerInfo.name"
						border="none"
						placeholder="请填写您的真实姓名"
					></u--input>
				</u-form-item>
				
				<!-- 性别 -->
				<u-form-item
					label="性别"
					prop="gender"
					borderBottom
				>
					<u-radio-group v-model="houseOwnerInfo.gender" placement="row">
						<u-radio shape="circle" label="男" name="男" :customStyle="{marginRight: '85rpx'}"></u-radio>
						<u-radio shape="circle" label="女" name="女"></u-radio>
					</u-radio-group>
				</u-form-item>
				
				<!-- 手机号 -->
				<u-form-item
					label="手机号"
					prop="mobile"
					borderBottom
				>
					<u--input
						v-model="houseOwnerInfo.mobile"
						border="none"
						type="number"
						placeholder="请输入您的手机号"
					></u--input>
					
					<view class="u-demo-block__content" slot="right">
						<u-code
							ref="uCode2"
							@change="codeChange"
							keep-running
							start-text="获取验证码"
							seconds="60"
						></u-code>
						<text
							@tap="getCode"
							:text="tips"
							class="u-page__code-text"
						>{{tips}}</text>
					</view>
				</u-form-item>
				
				<!-- 验证码 -->
				<u-form-item
					label="验证码"
					prop="code"
					borderBottom
				>
					<u--input
						v-model="houseOwnerInfo.code"
						border="none"
						type="number"
						placeholder="请输入手机验证码"
					></u--input>
				</u-form-item>
			</u--form>
		</view>
		
		<view class="upload-title">
			<u-cell-group>
				<u-cell
				  size="large"
				  title="上传本人身份证照片">
					<text slot="label" class="upload-text-label">
						请拍摄证件原件，并使照片中证件边缘完整，文字清晰，光线均匀。
					</text>
				</u-cell>
			</u-cell-group>
			
			<u-upload
				:fileList="fileList0"
				@afterRead="afterRead"
				@delete="deletePic"
				name="0"
				:maxCount="1"
				width="690rpx"
				height="340rpx"
				:previewImage="true"
				multiple
				uploadIcon="plus"
				uploadText="上传人像面照片"
			>
				
			</u-upload>
			
			<u-upload
				:fileList="fileList1"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				:maxCount="1"
				width="690rpx"
				height="340rpx"
				previewImage="true"
				multiple
				uploadIcon="plus"
				uploadText="上传国徽照片"
			>
				
			</u-upload>
		</view>
		
		<life-button icon="../../static/icon/check.png" @click="commitCheck" >提交审核</life-button>
		
		<!-- 模拟短信提示 -->
		<u-notify @click.native="copyCode" ref="uNotify"></u-notify>
	</view>
</template>

<script>
	import toast from '@/utils/toast.js'
	import { sendCode } from '@/api/login.js'
	import { commitCheck } from '@/api/add-house-info.js'
	export default {
		data() {
			return {
				title: '',
				houseOwnerInfo: {
					name: '',
					gender: '男',
					mobile: '',
					code: ''
				},
				IDcardPhoto: [],
				// communityInfo: {},
				code: '',
				rules: {
					'name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					},
					mobile: [
						{
							required: true, 
							message: '请输入手机号',
							trigger: ['change','blur'],
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// uni.$u.test.mobile()就是返回true或者false的
								return uni.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change','blur'],
						}
					],
					'code': [{
						required: true,
						message: '请输入验证码',
						trigger: ['change', 'blur'],
					}, {
						pattern: /^\d{6}$/,
						message: '验证码格式不正确',
						trigger: ['change', 'blur'],
					}]
				},
				fileList0: [],
				fileList1: [],
				tips: ''
			}
		},
		
		// watch: {
		// 	IDcardPhoto: {
				
		// 	}
		// },
		
		methods: {
			
			// 上传图片
			async afterRead(event) {
				console.log(event);
				// this.IDcardPhoto.push(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				            // const item = event.file[0];
							let lists = [].concat(event.file)
							lists.map((item) => {
								this[`fileList${event.name}`].push({
									...item,
									// //提示上传中
									// status: 'uploading',
									// message: '上传中'
								});
								
								// 获取本地读取文件路径
								const url = item.url;
								//result为上传成功的响应数据
								this.uploadFilePromise(url,event.name);
								// let result = await this.uploadFilePromise(url,event.name);
							})
				            
				            //上传成功提示，以及回显
				            // this['fileList'].splice(
				            //     0,
				            //     1,
				            //     Object.assign(item, {
				            //         status: 'success',
				            //         message: '上传成功',
				            //         // 二进制文件流用于预览图片
				            //         url: result
				            //     })
				            // );
			},
			
			deletePic(e) {
			    // this['fileList'].splice(0, 1);
				console.log(e);
				this[`fileList${e.name}`].splice(e.index, 1)
			},
			
			uploadFilePromise(url, name) {
				// 获取上传域名
				// const domain = this.loginForm.serveIp;
				// token
				console.log('url', url);
				let token = uni.getStorageSync('userToken').token
				// 请求头
				var header = {
					Authorization: 'Bearer ' + token
				};
				
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						// 完整上传路径 H5端需要解决跨域问题
						url: 'https://live-api.itheima.net/upload',
						// 本地上传读取到的url
						filePath: url,
						name: 'file',
						// 请求头
						header: header,
						// 附加表单对象
						formData: {
							file: url
						},
						success: res => {
							console.log('suc', res);
							// 这里res是普通对象，但是res.data为JSON字符串，需要转一下
							const result = JSON.parse(res.data);
							
							// 获取上传成功后的文件地址
							const formUrl = result.data.url;
							
							// 赋值表单数据（后台需要）
							console.log(formUrl);
							// this.dataForm.picture = formUrl;
							this.IDcardPhoto.push({
								url: formUrl,
								name
							})
							
							// 把文件的二进制对象抛出去用于图片预览
							resolve(res.data.data);
						}
					});
				});
			},
			
			// 验证码
			codeChange(text) {
				// console.log(text);
				this.tips = text
			},
			
			async getCode() {
				try{
					// await Promise.reject(3000)
					let errorflag = false
					await this.$refs.form1.validateField('mobile',(errorsRes)=> {
						console.log(errorsRes);
						
						if (errorsRes.length) {
							// Promise.reject(errorsRes[0].message)
							console.log(123);
							return errorflag = errorsRes
						}
					})
					
					if (errorflag) {
						console.log(errorflag);
						throw new Error( errorflag[0].message )
					}
					
					// 通知验证码组件内部开始倒计时
					this.$refs.uCode2.start();
					
					// 手机号合法，发请求
					const res = await sendCode(this.houseOwnerInfo.mobile)
					// message
					const message = `【享+生活】验证码：${res.data.code}.您正在使用短信验证码功能，验证码提供他人可能导致账号被盗，请勿转发或泄漏。`
					this.code = res.data.code
					// 短信提示
					this.$refs.uNotify.show({
						top: 10,
						type: 'success',
						message: message,
						duration: 1000 * 6,
						fontSize: 14
					})
					// 震动
					uni.vibrateLong()
					
				}catch(e){
					//TODO handle the exception
					// console.log(e);
					toast.error({
						title: e.message
					})
				}
			},
			
			async commitCheck() {
				const res = await commitCheck({
					...this.communityInfo,
					name: this.houseOwnerInfo.name,
					gender: this.houseOwnerInfo.gender === '男' ? 1 : 0 ,
					mobile: this.houseOwnerInfo.mobile,
					idcardFrontUrl: this.IDcardPhoto.filter(item => item.name == 0)[0].url,
					idcardBackUrl: this.IDcardPhoto.filter(item => item.name == 1)[0].url
				})
				console.log('shenhe',res);
			},
			
			// 复制
			copyCode() {
				uni.setClipboardData({
					data: this.code
				})
			}
		},
		
		computed: {
			communityInfo(){
				let tempArr = this.title.split(' ')
				return { 
					point: tempArr[0],
					building: tempArr[1],
					room: tempArr[2],
				}
			}
		},
		
		onLoad(options) {
			console.log(options)
			this.title = options.title
			// console.log(options.title.split(' '));
		},
		
		onReady() {
			this.$refs.form1.setRules(this.rules)
		}
	}
</script>

<style lang="scss" scoped>
	.add-house-info {
		height: 100%;
		background-color: #FAFAFA;
		padding-bottom: 670rpx;

		.house-title {
			.title {
				padding: 30rpx;
				color: #979797;
				font-size: 24rpx;

			}

			.content {
				padding: 30rpx;
				color: #333333;
				font-size: 28rpx;
				line-height: 1.5;
				letter-spacing: 0rpx;
				background-color: #fff;

			}
		}

		.houseOwner-info {
			.title {
				padding: 30rpx;
				color: #979797;
				font-size: 24rpx;
				// margin-bottom: 30rpx;
			}
		}
	}
	
	::v-deep .u-form-item__body {
		background-color: white;
		padding: 0 !important;
		height: 102rpx;
	}
	
	::v-deep .u-form-item {
		background-color: white !important;
	}
	
	.upload-title {
		background-color: white;
		margin-top: 30rpx;
		// padding-left: 30rpx;
		
		.upload-text-label {
			color: #C3C3C5;
			font-family: PingFang SC;
			font-weight: regular;
			font-size: 22rpx;
			line-height: 1.5;
			letter-spacing: 0rpx;
			text-align: left;
			margin-top: 12rpx
		}
	}
	
	
	::v-deep .u-upload {
		// background-color: red;
		margin-top: 20rpx;
		padding-left: 30rpx !important;
		padding-right: 30rpx;
		box-sizing: border-box;
	}
	
	.u-page {
		&__code-text {
			color: $u-primary;
			font-size: 15px;
		}
	}
	
	.u-demo-block__content {
		@include flex;
		margin-right: 50rpx;
	}
</style>
